'''
Created on May 15, 2010

iur - Universal Web Remote targetted for iphone
Copyright (C) 2010 forteresce@gmail.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

'''

from player.eventhandler import PlayerEventHandler
from model.song import Song
import dbus
import base64

class BansheeEventHandler(PlayerEventHandler):
    '''
    The event handler for Banshee player
    '''
    DBUS_NAME   = 'org.bansheeproject.Banshee'
    PLAYER_ENGINE_DBUS_OBJECT = '/org/bansheeproject/Banshee/PlayerEngine'
    PLAYBACK_CONTROLLER_DBUS_OBJECT = '/org/bansheeproject/Banshee/PlaybackController'
    PLAY_QUEUE_DBUS_OBJECT = '/org/bansheeproject/Banshee/SourceManager/PlayQueue'
    
    def __init__(self):
        self.playerEngine = self.session_bus.get_object(self.DBUS_NAME, self.PLAYER_ENGINE_DBUS_OBJECT)
        self.playbackController = self.session_bus.get_object(self.DBUS_NAME, self.PLAYBACK_CONTROLLER_DBUS_OBJECT)
        self.playQueue = self.session_bus.get_object(self.DBUS_NAME, self.PLAY_QUEUE_DBUS_OBJECT)
        pass
    
    def play(self):
        self.playerEngine.Play()
    
    def pause(self):
        self.playerEngine.Pause()

    def next(self):
        self.playbackController.Next(True)

    def prev(self):
        self.playbackController.Previous(True)
        
    def getCurrentSong(self):
        if self.playerEngine.GetCurrentState() == 'idle':
            return
        
        track = self.playerEngine.GetCurrentTrack()
        
        # clean up
        vals = ('name','artist','album')
        for key in [key for key in vals if key not in track]:
            track[key] = 'Unknown'
            
        return Song(track['name'], track['artist'], track['album'])    

    def addSongToQueue(self, id):
        uri = base64.b64decode(id)
        self.playQueue.EnqueueUri(uri, False)

    def volumeUp(self):
        volume = self.playerEngine.GetVolume()
        if volume < 90:
            volume += 10
        else:
            volume = 100
        self.playerEngine.SetVolume(dbus.UInt16(volume))
        return self.playerEngine.GetVolume()

    def volumeDown(self):
        volume = self.playerEngine.GetVolume()
        if volume > 10:
            volume -= 10
        else:
            volume = 0
        self.playerEngine.SetVolume(dbus.UInt16(volume))
        return self.playerEngine.GetVolume()

#====================================================================================================

from player.collectionhandler import PlayerCollectionHandler
import sqlite3
from model.album import Album
import os

class BansheeCollectionHandler(PlayerCollectionHandler):
    '''
    The collection handler for Banshee player
    '''
    DB_PATH = os.path.join(os.path.expanduser('~'), '.config', 'banshee-1', 'banshee.db')
    
    def __init__(self):
        self.conn = sqlite3.connect(self.DB_PATH)
        
    def getAlbums(self, startsWith='a'):
        albums = []
        try:
            cur = self.conn.cursor()
            
            cur.execute("""
                        SELECT
                            AlbumID, Title
                        FROM
                            CoreAlbums
                        WHERE
                            TitleLowered like '%s%%'
                        ORDER BY
                            Title
                        """ % startsWith.lower())
            
            for (id, title) in cur:
                if title is None:
                    title = 'Unknown'
                album = Album(id, title)
                albums.append(album)
                
        except Exception, e:
            print str(e)

        return albums
    
    def getSongsInAlbum(self, albumId):
        songs = []
        try:
            cur = self.conn.cursor()
            
            cur.execute("""
                        SELECT
                            t.uri, t.Title, al.title, ar.name
                        FROM
                            CoreTracks t, CoreAlbums al, CoreArtists ar
                        WHERE 
                            t.AlbumID = %s AND t.AlbumID = al.AlbumID AND ar.ArtistID = t.ArtistID
                        ORDER BY
                            t.Title
                        """ % albumId)
            
            for (uri, title, album, artist) in cur:
                if title is None:
                    title = 'Unknown'
                if album is None:
                    album = 'Unknown'
                if artist is None:
                    artist = 'Unknown'
                song = Song(title, artist, album, base64.b64encode(uri))
                songs.append(song)
                
        except Exception, e:
            print str(e)

        return songs
